<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery1">
        <a-row :gutter="24">
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="门店" :required="true">
              <a-cascader
                :options="departModel.departTreeOptions"
                :showSearch="true"
                expand-trigger="hover"
                placeholder
                :fieldNames="departModel.fieldNames"
                style="width: 200px"
                v-model="queryParam.selecteddeparts"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="品牌">
              <a-select allowClear defaultValue="1" v-model="queryParam.brandCode" showSearch
                :filter-option="filterOption" :not-found-content="null">
                <a-select-option v-for="item in brandList" :key="item.id" :value="item.brandCode">
                  {{ item.brandName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="SKU编码">
              <a-input placeholder v-model="queryParam.itemSku" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="商品编码">
              <a-input placeholder v-model="queryParam.itemCode" allowClear></a-input>
            </a-form-item>
          </a-col>

          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="商品名称">
              <a-input placeholder v-model="queryParam.itemName" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="7" :md="8" :sm="24">
            <a-form-item label="零售价格">
              <!-- <a-input-number v-model="queryParam.price" style="width: 100%"></a-input-number> -->
              <a-input-group compact>
                <template v-if="inputType == 'between'">
                  <a-input-number
                    style="width: 100px; text-align: center"
                    placeholder="最小值"
                    v-model="queryParam.beginPrice"
                    allowClear
                  />
                  <a-input
                    style="width: 30px; border-left: 0; pointer-events: none; backgroundcolor: #fff"
                    placeholder="~"
                    disabled
                  />
                  <a-input-number
                    style="width: 100px; text-align: center; border-left: 0"
                    placeholder="最大值"
                    v-model="queryParam.endPrice"
                    allowClear
                  />
                </template>
              </a-input-group>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="价格尾数">
              <a-select v-model="queryParam.priceTail" allowClear>
                <a-select-option
                  v-for="(item, index) in priceTail"
                  :key="index"
                  :value="item.value"
                >{{ item.text }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="所属分类">
              <a-cascader
                :options="cateModel.cateTreeOptions"
                :showSearch="true"
                expand-trigger="hover"
                placeholder
                :fieldNames="cateModel.cateFileName"
                style="width: 200px"
                v-model="queryParam.selectCates"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="季节">
              <a-select v-model="queryParam.itemSession" allowClear>
                <a-select-option
                  v-for="(item, index) in itemSession"
                  :key="index"
                  :value="item.value"
                >{{ item.text }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="类型">
              <a-select v-model="queryParam.itemType" allowClear>
                <a-select-option
                  v-for="(item, index) in itemType"
                  :key="index"
                  :value="item.value"
                >{{ item.text }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="7" :md="8" :sm="24">
            <a-form-item label="上架时间">
              <a-range-picker
                :ranges="{ 今天: [moment(), moment()], 本月: [moment().startOf('month'), moment().endOf('month')] }"
                v-model="shelevsDateRange"
                @change="handleChange"
              />
            </a-form-item>
          </a-col>

          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="状态">
              <a-select v-model="queryParam.pStatus" allowClear>
                <a-select-option
                  v-for="(item, index) in pStatus"
                  :key="index"
                  :value="item.value"
                >{{ item.text }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="买手">
              <a-input placeholder="" v-model="queryParam.buyer" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="供应商">
              <a-input placeholder="" v-model="queryParam.supplier" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="上市年份">
              <a-select v-model="queryParam.itemYear" allowClear>
                <a-select-option v-for="(item, index) in years" :key="index" :value="item.value">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item>
              <a-checkbox v-model="queryParam.hasStock">库存大于0</a-checkbox>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery1" icon="search">查询</a-button>
              <a-button
                type="default"
                @click="searchReset1"
                icon="reload"
                style="margin-left: 8px"
              >重置</a-button>
            </span>
          </a-col>
          
        </a-row>
      </a-form>
    </div>
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="download" :loading="exporting" @click="handleExport('SKU数据')">导出Excel</a-button>
    </div>
    <!--总数据展示began -->
    <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
      <span class="sum">
        商品剩余库存(件)
        <span class="b">{{orderSum.sum}}</span>
      </span>
    </div>
    <!--总数据展示end -->
    <!-- 操作按钮区域 -->

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <span slot="action" slot-scope="text, record">
          <!-- <a @click="handleEdit(record)">编辑</a> -->
        </span>
        <span slot="pstatus" slot-scope="text, record">
          <span v-if="text === 1">上架</span>
          <span v-else>下架</span>
        </span>
        <span slot="photo" slot-scope="text, record">
          <a-avatar
            shape="square"
            :src="text + '?x-oss-process=image/resize,w_50,h_50'"
            @click="text ? previewImgObject([text]) : () => {}"
          ></a-avatar>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <supplyProduct-modal ref="modalForm" @ok="modalFormOk"></supplyProduct-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import SupplyProductModal from './modules/SupplyProductModal'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { queryDepartTreeList1, queryProductCateList,queryMerchantBussList } from '@/api/api'
import { getAction, downFile } from '@/api/manage'
import moment from 'moment'
import { previewImgObject } from '@/utils/util'

export default {
  name: 'SupplyProductList',
  mixins: [JeecgListMixin],
  components: {
    SupplyProductModal
  },
  data() {
    return {
      disableMixinCreated: true,
      moment,
      previewImgObject,
      inputType: 'between',
      exporting:false,
      departModel: {
        departTreeOptions: [],
        fieldNames: { label: 'title', value: 'value', children: 'children' }
      },
      cateModel: {
        cateTreeOptions: [],
        cateFileName: { label: 'name', value: 'cd', children: 'children' }
      },
      shelevsDateRange: [],
      orderSum: {
        sum: 0
      },
      itemSession: [
        { text: '春', value: '春' },
        { text: '夏', value: '夏' },
        { text: '秋', value: '秋' },
        { text: '冬', value: '冬' },
        { text: '未知', value: '未知' },
      ],
      itemType: [
        { text: '正价', value: '正价' },
        { text: '砍货', value: '砍货' },
        { text: '代卖', value: '代卖' }
      ],
      priceTail: [
        { text: '0', value: '0' },
        { text: '1', value: '1' },
        { text: '2', value: '2' },
        { text: '3', value: '3' },
        { text: '4', value: '4' },
        { text: '5', value: '5' },
        { text: '6', value: '6' },
        { text: '7', value: '7' },
        { text: '8', value: '8' },
        { text: '9', value: '9' }
      ],
      yesNoState: [
        { text: '是', value: '1' },
        { text: '否', value: '0' }
      ],
      pStatus: [
        { text: '上架', value: '1' },
        { text: '下架', value: '0' }
      ],
      brandList: [
      ],
      years: [],
      description: '商品SKU管理管理页面',
      // 表头
      columns: [
        {
          title: '所属机构',
          align: 'center',
          dataIndex: 'orgName'
        },
        {
          title: '所属门店',
          align: 'center',
          dataIndex: 'shopName',
          sorter: true
        },
        {
          title: '商品编码',
          align: 'center',
          dataIndex: 'itemCode'
        },
        {
          title: '产品主图',
          align: 'center',
          dataIndex: 'photo',
          scopedSlots: { customRender: 'photo' }
        },
        {
          title: '商品名称',
          align: 'center',
          dataIndex: 'itemName'
        },
        {
          title: 'SKU编码',
          align: 'center',
          dataIndex: 'itemSku'
        },
        {
          title: '季节',
          align: 'center',
          dataIndex: 'itemSession'
        },
        {
          title: '类型',
          align: 'center',
          dataIndex: 'itemType'
        },
        {
          title: '颜色',
          align: 'center',
          dataIndex: 'itemColor',
          sorter: true
        },
        {
          title: '尺码',
          align: 'center',
          dataIndex: 'itemSize',
          sorter: true
        },
        {
          title: '所属分类',
          align: 'center',
          dataIndex: 'itemCateName'
        },
        {
          title: '供应价',
          align: 'center',
          dataIndex: 'supplyPrice',
          sorter: true
        },
        {
          title: '零售价',
          align: 'center',
          dataIndex: 'markPrice',
          sorter: true
        },
        {
          title: '入库总库存(件)',
          align: 'center',
          dataIndex: 'ioTotal'
        },
        {
          title: '剩余库存(件)',
          align: 'center',
          dataIndex: 'ioQty',
          sorter: true
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'pstatus',
          scopedSlots: { customRender: 'pstatus' }
        },
        {
          title: '上架时间',
          align: 'center',
          dataIndex: 'createTime'
        },
        {
          title: '品牌',
          align: 'center',
          dataIndex: 'brandName'
        },
        {
          title: '买手',
          align: 'center',
          dataIndex: 'buyer'
        },
        {
          title: '供应商',
          align: 'center',
          dataIndex: 'supplier'
        },
        {
          title: '上市年份',
          align: 'center',
          dataIndex: 'itemYear'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/stock/supplyProduct/list',
        queryStatistic: '/stock/supplyProduct/queryStatistic',
        shopListUrl: '/sys/sysDepart/getMyDepartList',
        exportXls:'/stock/supplyProduct/exportXls',
      }
    }
  },
  computed: {},
  created() {
    this.queryParam.pStatus = '1'
    this.loadDepartTree()
    this.loadCateTree()
    this.yearChange()
    this.loadBrandList()
  },
  methods: {
    searchReset1() {
      let selecteddeparts = this.queryParam.selecteddeparts
      let selectCates = this.queryParam.selectCates
      this.queryParam = {}
      this.$set(this.queryParam, 'selecteddeparts', selecteddeparts)
      this.$set(this.queryParam, 'selectCates', selectCates)
      this.searchQuery1()
    },
    loadBrandList() {
      this.brandList = []
      queryMerchantBussList({ 'bussType': 'BRAND' }).then((res) => {
        if (res.success) {
          for (let a of res.result) {
            this.brandList.push({ brandName: a.bussName, brandCode: a.bussCode })
          }
        }
      })
    },
    querySum() {
      console.log('into querySum')
      getAction(this.url.queryStatistic, this.queryParam).then(res => {
        if (res.success) {
          this.orderSum = res.result
        }
      })
    },
    assembleQueryParam() {
      console.log('查询参数是：', this.queryParam.selecteddeparts, this.queryParam.selectCates)

      let selecteddeparts = this.queryParam.selecteddeparts
      if (selecteddeparts && selecteddeparts.length == 2) {
        this.queryParam.orgIds = selecteddeparts[0]
        this.queryParam.shopIds = selecteddeparts[1] == 0 ? null : selecteddeparts[1]

      } else {
        this.queryParam.orgIds = null
        this.queryParam.shopIds = null
        
      }

      let selectCates = this.queryParam.selectCates
      if(selectCates && selectCates.length > 0){
        this.queryParam.cateParent = selectCates[0]
        this.queryParam.cateChild = selectCates[1] == 0 ? null : selectCates[1]
      }else{
        this.queryParam.cateParent = null
        this.queryParam.cateChild = null
      }


      let orgIds = this.queryParam.orgIds
      if (!orgIds) {
        this.$message.warning('请选择机构再查询')
        return false
      }
      return true
    },
    searchQuery1() {
      
      if (!this.assembleQueryParam()) {
        return
      }

      // 在此调用查询数量
      this.querySum()
      this.loadData(1)
    },
    handleChange(date, dateString) {
      this.queryParam.beginTime = dateString[0]
      this.queryParam.endTime = dateString[1]
    },
    loadDepartTree() {
      queryDepartTreeList1().then(res => {
        if (res.success) {
          let departList = res.result
          console.log('门店信息' + departList)
          if (departList.length == 1 && departList[0].orgType == 1) {
            departList = departList[0].children
          }
          this.departModel.departTreeOptions = departList

          this.departModel.departTreeOptions.forEach(x => {
            if (!x['children']) {
              x['children'] = []
            }
            let allShop = { title: '全部门店', value: '0' }
            x['children'].unshift(allShop)
          })

          this.$set(this.queryParam, 'selecteddeparts', [departList[0].id, '0'])
        }
        this.searchQuery1()
      })
    },
    loadCateTree() {
      queryProductCateList().then(res => {
        if (res.success) {
          let cateList = res.result
          console.log('---cateList---', cateList)
          // if (cateList.length == 1 && cateList[0].orgType == 1) {
          //   cateList = cateList[0].children
          // }
          this.cateModel.cateTreeOptions = cateList
          console.log('---------------------cateTreeOptions', cateList[0].name)
          this.cateModel.cateTreeOptions.forEach(x => {
            if (!x['children']) {
              x['children'] = []
            }
            let cateShop = { name: '全部分类', cd: '0' }
            x['children'].unshift(cateShop)
          })
          // this.$set(this.queryParam, 'selectCates', [cateList[0].id, '0'])
        }
      })
    },
    yearChange () {
      var myDate = new Date()
      var year = myDate.getFullYear() 

      this.years = []
      
      for (let i = 0; i < 10; i++) {
        this.years.push({value: (year - i), text: (year - i)})
      }
    },
    handleExport(fileName) {
      if (!this.assembleQueryParam()) {
        return
      }

      if(!this.queryParam.orgIds){
        this.$message.warning("市场必选")
        return false
      }

      this.exporting = true
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let param = this.getQueryParams()
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      console.log('导出参数', param)
      let that = this
      downFile(this.url.exportXls, param).then((data) => {
        that.exporting = false
        if (!data) {
          that.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }

      })

      setTimeout(() => {
        that.exporting = false
      }, 20 * 1000)
    },
  }
}
</script>
<style scoped lang="less">
@import '~@assets/less/common.less';
.sum {
  margin-right: 24px;
  .b {
    font-weight: 600;
    color: @primary-color;
  }
}
</style>